import { Button } from 'antd'
import { useState } from 'react'
import { useRequest } from 'alova/client'
import { useEventEmitter, useMount } from 'ahooks'

import { Http } from '../../Utils/Api'
import { refreshStore } from '../../Config/zustand'
import { getInitMenu } from '../../Utils/TableConfig'
import { DevextremeTemplate } from '../../Utils/Devextreme'

// 默认页码配置
const defaultPagig = { pageIndex: 1, pageSize: 10000, isContains: '是' }
const pageConfig = { url: 'getProjectInfo', page: 'TwoPageOrg' }

const ProjectList = ({ init, Off }) => {
    const { updateRefresh } = refreshStore()

    const [selectRowkeys, setSelectRowkeys] = useState()
    const { send } = useRequest(({ url, params }) => Http({ url, params }), { immediate: false })

    const [Config, setConfig] = useState()
    const [dataSource, setDataSource] = useState()

    useMount(async () => {
        const { data, page } = await getInitMenu({ url: pageConfig.url, config: pageConfig.page, defaultPagig })
        const { list } = data.data
        page.tableConfig.selectionMode = 'multiple'
        page.tableConfig.selectionShowCheckBoxesMode = 'onClick'
        send({ url: 'getUserManageProject', params: { userUuid: init.uuid } }).then(res => {
            setConfig(page)
            setDataSource(list)
            setSelectRowkeys(res.data)
        })
    })

    const onSubmit = () => {
        const params = selectRowkeys.map(key => ({ userUuid: init.uuid, manageProjectUuid: key }))
        send({ url: 'posUserManageProject', params }).then(res => {
            updateRefresh(new Date().getTime())
            Off()
        })
    }

    const DevEvent = useEventEmitter()
    DevEvent.useSubscription(val => {
        const { type, data } = val
        if (type === 'onSelectionChanged') setSelectRowkeys(data)
    })

    return (
        <div className="CommonMenu RoleList">
            <div className='Table'>
                {selectRowkeys && dataSource && Config &&
                    <DevextremeTemplate
                        dataSource={dataSource}
                        config={Config}
                        selectRowkeys={selectRowkeys}
                        DevEvent={DevEvent}
                        ColumnOptions={() => []}
                    />
                }
            </div>
            <div className='Submit'>
                <Button type='primary' size='large' onClick={onSubmit}>保存</Button>
            </div>
        </div>
    );
};

export default ProjectList;